
#  -*-coding:utf-8 -*-
from datetime import *
from flask import Flask, render_template, url_for, session, flash
from flask_bootstrap import Bootstrap
from flask_moment import Moment
from flask_wtf import FlaskForm
from flask import redirect
from wtforms import StringField, SubmitField
from wtforms.validators import Required
from flask_script import Manager
from flask_sqlalchemy import SQLAlchemy
import os

app=Flask(__name__)
app.config['SECRET_KEY'] = 'hard to guess string'

basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] =\
'sqlite:///' + os.path.join(basedir, 'data.sqlite')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
db=SQLAlchemy(app)
bootstrap=Bootstrap(app)
Moment=Moment(app)
manager=Manager(app)

class form1(FlaskForm):
	info_information=StringField('填写你要发布的信息：',validators=[Required()])
	submit = SubmitField('发布')

class form2(FlaskForm):
	search_information=StringField('填写你要搜索的信息：',validators=[Required()])
	submit = SubmitField('搜索')


class Info_sql(db.Model):
  __tablename__='info_sqls'
  id = db.Column(db.Integer, primary_key=True, unique=False)
  info = db.Column(db.Text,unique=False)
  times = db.relationship('Time', backref='info_sql')
  def __repr__(self):
    return self.info
    
class Time(db.Model):
  __tablename__ = 'times'
  id = db.Column(db.Integer, primary_key=True, unique=False)
  time = db.Column(db.Text, unique=False)
  info_sql_id = db.Column(db.Integer, db.ForeignKey('info_sqls.id'))
  def __repr__(self):
    return self.time



@app.route('/',methods=['GET','POST'])
def ask():
	if not os.path.exists("data.sqlite"):
		db.create_all()
	info_form=form1()
	search_form=form2()
	information=Info_sql.query.all()[::-1]
	time=Time.query.all()[::-1]
	num=[]
	if info_form.validate_on_submit():
		#global yd
		# session['information']=form.information.data
		for i in information:
			if (str(i)==info_form.info_information.data):
				flash('信息已有发表历史，请检查！','warning')
				return redirect(url_for('ask'))
		info=Info_sql(info=info_form.info_information.data)
		time=Time(time=str(datetime.today()))
		db.session.add(info)
		db.session.add(time)
		db.session.commit()
		flash('恭喜你！发布成功！','success')

		#return redirect(url_for('post'))
				
		return redirect(url_for('ask'))
	# information=information.split('---time')
	if search_form.validate_on_submit():	
		for i in information:
			if (search_form.search_information.data in str(i)):
				num.append(information.index(i))
		return render_template('result.html', Data=information,Time_data=time, num=num)
	return render_template('post.html', form1=info_form, form2=search_form, Data=information, Time_data=time)

# @app.route('/result',methods=['GET','POST'])
# def result():
	
# 	return render_template('result.html',form=form, Data=information)


if __name__=='__main__':
	#app.run(debug=True)
       manager.run()





